<?php

/**
 * This is the model class for table "system".
 *
 * The followings are the available columns in table 'system':
 * @property string $id
 * @property string $name
 * @property string $value
 * @property string $note
 * @property string $created
 * @property string $updated
 * @property integer $del_flg
 */
class System extends CActiveRecord
{
    /** @var array Configuration cache */
    protected static $_CONF;
    /** @var array Configuration IDs cache */
    protected static $_CONF_IDS;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return System the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'system';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('del_flg', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>50),
			array('value, note, created, updated', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, value, note, created, updated, del_flg', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'value' => 'Value',
			'note' => 'Note',
			'created' => 'Created',
			'updated' => 'Updated',
			'del_flg' => 'Del Flg',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('value',$this->value,true);
		$criteria->compare('note',$this->note,true);
		$criteria->compare('created',$this->created,true);
		$criteria->compare('updated',$this->updated,true);
		$criteria->compare('del_flg',$this->del_flg);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    public static function loadConfiguration()
    {
        self::$_CONF = array();
        self::$_CONF_IDS = array();

        $criteria=new CDbCriteria;
        $criteria->addCondition('del_flg = 0');
        $result = self::model()->findAll($criteria);

        if ($result){
            foreach($result as $value){
                self::$_CONF_IDS[$value->name] = (int)$value->id;
                self::$_CONF[$value->name] = $value->value;
            }
        }
    }

    /**
     * Get a single configuration value
     *
     * @param string $key Key wanted
     * @return string Value
     */
    public static function get($key)
    {
        if (isset(self::$_CONF[$key]))
            return self::$_CONF[$key];
        return false;
    }

    /**
     * Update configuration key and value into database (automatically insert if key does not exist)
     *
     * @param string $key Key
     * @param mixed $values $values is an array if the configuration is multilingual, a single string else.
     * @param boolean $html Specify if html is authorized in value
     *
     * @return boolean Update result
     */
    public static function updateValue($key, $values, $html = false)
    {
        if ($key == null)
            return;

        $current_value = self::get($key);

        /* Update classic values */
        if (!is_array($values))
        {
            /* If the current value exists but the _CONF_IDS[$key] does not, it mean the value has been set but not save, we need to add */
            if ($current_value !== false && isset(self::$_CONF_IDS[$key]))
            {
                $values = Common::pSQL($values, $html);

                /* Do not update the database if the current value is the same one than the new one */
                if ($values == $current_value)
                    $result = true;
                else
                {
                    $result = self::model()->findByPk((int)self::$_CONF_IDS[$key], 'del_flg=0');
                    $result->value = $values;

                    if ($result->save())
                        self::$_CONF[$key] = stripslashes($values);
                }
            }
        }

        return (bool)$result;
    }

}